﻿using Farming.Domain;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Farming.Application
{
    public class SoftDeleteInterceptor:SaveChangesInterceptor
    {
        private readonly IHttpContextAccessor httpContextAccessor;
        public SoftDeleteInterceptor(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor;
        }
        public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
    {
        OnSavingChanges(eventData, httpContextAccessor);
        return base.SavingChanges(eventData, result);
    }
    public override ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, InterceptionResult<int> result,
        CancellationToken cancellationToken = new CancellationToken())
    {
        OnSavingChanges(eventData, httpContextAccessor);
        return base.SavingChangesAsync(eventData, result, cancellationToken);
    }
    private static void OnSavingChanges(DbContextEventData eventData, IHttpContextAccessor httpContextAccessor)
    {
        ArgumentNullException.ThrowIfNull(eventData.Context);
        eventData.Context.ChangeTracker.DetectChanges();

        //var currentUserId = accountService.GetCurrentUserId();
        //    var currentUsername = accountService.GetCurrentUsername();
               
            var claimsPrincipal = httpContextAccessor.HttpContext.User;
            var customClaimType = "id";
            var userId = claimsPrincipal.FindFirst(customClaimType)?.Value;
            var username = claimsPrincipal.FindFirst(ClaimTypes.Name)?.Value;

            foreach (var entityEntry in eventData.Context.ChangeTracker.Entries())
        {

                if (entityEntry.State == EntityState.Deleted && entityEntry.Entity is ISoftDeleteEntityWithDeleted auditFields)
                {
                    auditFields.IsDeleted = true;
                    auditFields.DeleteById = int.Parse(userId);
                    auditFields.DeleteByName = username;
                    auditFields.DeleteTime = DateTime.UtcNow;
                    entityEntry.State = EntityState.Modified;
                }
                 if (entityEntry is { State: EntityState.Added, Entity: TraceabilityAdd AddEntity })
                {
                    AddEntity.CreateById = int.Parse(userId);
                    AddEntity.CreateByName = username;
                    AddEntity.CreateTime = DateTime.UtcNow;
                    entityEntry.State = EntityState.Added;
                }
                if (entityEntry is { State: EntityState.Modified, Entity: TraceabilityModify ModifyEntity })
                {
                    ModifyEntity.UpdateById = int.Parse(userId);
                    ModifyEntity.UpdateByName = username;
                    ModifyEntity.UpdateTime = DateTime.UtcNow;
                    entityEntry.State = EntityState.Modified;
                }
                
            }
    }

    }
}
